/**
 * Acestek.com.cn Inc.
 * Copyright (c) 2004-2015 All Rights Reserved.
 */
package test;

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import com.decoder.BASE64Decoder;
import com.decoder.BASE64Encoder;


/**
 * 总体说明
 * <p>
 * <p>具体说明</p>
 *
 * @author Jxx
 * @version $Id: AES.java,v 0.1 2015年7月30日 下午6:29:50 Exp $
 */
public class AES {

    /**
     * AES加密
     *
     * @param data     待加密的数据
     * @param password 加密密钥（16个字符）
     * @return
     */
    public static String encrypt(String data, String password) {
        try {
            //创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            //初始化
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            //加密数据
            byte[] result = cipher.doFinal(data.getBytes());
            return new BASE64Encoder().encode(result);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return null;
    }


    /**
     * AES解密
     *
     * @param data     待解密的数据
     * @param password 解密密钥
     * @return
     */
    public static String decrypt(String data, String password) {
        try {
            //创建密码器
            Cipher cipher = Cipher.getInstance("AES");
            //初始化
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            //解密数据
            byte[] yData =new BASE64Decoder().decodeBuffer(data);
            byte[] result = cipher.doFinal(yData);
            return new String(result);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }

        return null;
    }

    /**
     * 将 BASE64 编码的字符串 s 进行解码
     *
     * @param s
     * @return
     */
    public static String getFromBASE64(String s) {
        if (s == null)
            return "";
        BASE64Decoder decoder =new  BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * Base64编码加密
     *
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
            s = new BASE64Encoder().encode(b);
        }
        return s;
    }
}
